package com.dyz.leetcode._11_comprehensiveApplication;


public class _844_backspaceCompare {
    public boolean backspaceCompare(String s, String t) {

        StringBuffer newS = new StringBuffer();
        for(char c:s.toCharArray()){
            if(c!='#'){
                newS.append(c);
            }else {
                if(newS.length()>0){
                    newS.deleteCharAt(newS.length()-1);
                }
            }
        }

        StringBuffer newT = new StringBuffer();
        for(char c: t.toCharArray()){
            if(c!='#'){
                newT.append(c);
            }else {
                if(newT.length()>0){
                    newT.deleteCharAt(newT.length()-1);
                }
            }
        }

        return newS.toString().equals(newT.toString());
    }

    //  快慢指针
    public boolean backspaceCompare1(String s, String t) {
        return build(s).equals(build(t));
    }
    private String build(String s){
        char[] chars = s.toCharArray();
        int slow = -1;
        int fast = 0;
        while(fast<chars.length){
            if(chars[fast]!='#'){
                slow++;
                if(slow!=fast){
                    swap(chars, slow, fast);
                }
            }else if(slow>-1){
                slow--;
            }
            fast++;
        }
        return slow == -1?"":new String(chars, 0, slow+1);

    }
    public void swap(char[] chars, int slow, int fast){
        char tmp = chars[slow];
        chars[slow] = chars[fast];
        chars[fast] =tmp;
    }
}
